package operations

import (
	"errors"
	"github.com/sirupsen/logrus"
	"mydocker/utils"
	"os/exec"
)

func CommitContainer(containerID, imageName string) error {
	mntPath := utils.GetMerged(containerID)
	imageTar := utils.GetImage(imageName)
	exists, err := utils.PathExists(imageTar)
	if err != nil {
		logrus.Errorf("check is image [%s/%s] exist failed", imageName, imageTar)
		return err
	}
	if exists {
		return errors.New("image Already Exists")
	}
	logrus.Infof("commitContainer imageTar: %s", imageTar)

	if _, err := exec.Command("tar", "-czf", imageTar, "-C", mntPath, ".").CombinedOutput(); err != nil {
		logrus.Errorf("tar container image, file name: %s, err: %v", imageTar, err)
		return err
	}
	return nil
}
